package com.dayanxs.Service;

import com.dayanxs.Utils.AESCryptoUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AdminService {

    private final JdbcTemplate jdbcTemplate;

    public AdminService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public ResponseEntity<?> handleLogin(String username, String password) {
        // 使用参数化查询来避免SQL注入
        String sql = "SELECT COUNT(*) FROM admin WHERE username = ? AND password = ?";
        int count = jdbcTemplate.queryForObject(sql, new Object[]{username, password}, Integer.class);

        if (count == 1) { // 如果找到匹配的用户名和密码
            try {
                // 使用 AES 加密用户名和密码
                String combined = username + "." + password;
                String encryptedToken = AESCryptoUtil.encrypt(combined);

                Map<String, String> response = new HashMap<>();
                response.put("token", encryptedToken);

                return ResponseEntity.ok(response);
            } catch (Exception e) {
                return ResponseEntity.status(200).body("Encryption error");
            }
        } else {
            // 如果验证失败
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "账号或者密码错误！");

            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> systemInfo(String authorization) {
        String adminToken = getAdminToken(authorization);

        String novel_num_sql = "SELECT count(*) FROM `novel`";
        String chapter_num_sql = "SELECT count(*) FROM `novel_chapter`";
        String user_num_sql = "SELECT count(*) FROM `user`";

        if(!adminToken.isEmpty()) {
            try {
                if(isAdmin(adminToken)){
                    Integer total_novel = jdbcTemplate.queryForObject(novel_num_sql, Integer.class); // 总记录数
                    Integer total_chapter = jdbcTemplate.queryForObject(chapter_num_sql, Integer.class); // 总章节数
                    Integer total_user = jdbcTemplate.queryForObject(user_num_sql, Integer.class); // 总用户数
                    Map<String, Object> response = getStringObjectMap(total_novel, total_chapter, total_user);
                    return ResponseEntity.ok(response); // 返回分页结果和总页数
                }else{
                    Map<String, String> errorResponse = new HashMap<>();
                    errorResponse.put("message", "adminToken有误！");
                    return ResponseEntity.status(201).body(errorResponse);
                }
            } catch (Exception e) {
                // 错误处理
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "Error: " + e.getMessage());
                return ResponseEntity.status(201).body(errorResponse);
            }
        }else{
            return buildErrorResponse("adminToken为空!",201);
        }
    }
    public ResponseEntity<?> getUsersWithPagination(String authorization,int size, int page) {
        String adminToken = getAdminToken(authorization);
        if(adminToken.isEmpty()) {
            return buildErrorResponse("adminToken为空！",201);
        }
        if(!isAdmin(adminToken)){
            return buildErrorResponse("非管理员禁止操作！",201);
        }
        try {
            // 计算总记录数
            String countSql = "SELECT COUNT(*) FROM user";
            Integer totalRecords = jdbcTemplate.queryForObject(countSql, Integer.class); // 总记录数

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalRecords / size); // 总页数

            // 计算 OFFSET
            int offset = (page - 1) * size;

            // 分页查询
            String sql = "SELECT * FROM user ORDER BY id desc LIMIT ? OFFSET ?";
            List<Map<String, Object>> users = jdbcTemplate.queryForList(sql, new Object[]{size, offset});

            Map<String, Object> response = new HashMap<>();
            response.put("totalPages", totalPages); // 总页数
            response.put("users", users); // 小说数据

            return ResponseEntity.ok(response); // 返回分页结果和总页数

        } catch (Exception e) {
            // 错误处理
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Error fetching user: " + e.getMessage());
            return ResponseEntity.status(201).body(errorResponse);
        }
    }
    public ResponseEntity<?> getChaptersWithPagination(String authorization, int size, int page) {
        String adminToken = getAdminToken(authorization);
        if (adminToken.isEmpty()) {
            return buildErrorResponse("adminToken为空！", 201);
        }
        if (!isAdmin(adminToken)) {
            return buildErrorResponse("非管理员禁止操作！", 201);
        }
        try {
            // 计算总记录数
            String countSql = "SELECT COUNT(*) FROM novel_chapter";
            Integer totalRecords = jdbcTemplate.queryForObject(countSql, Integer.class); // 总记录数

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalRecords / size); // 总页数

            // 计算 OFFSET
            int offset = (page - 1) * size;

            // 分页查询
            String sql = "SELECT nc.id, nc.chapter_title, nc.chapter_content, nc.update_time, nc.chapter_novelID, n.* " +
                    "FROM novel_chapter nc " +
                    "INNER JOIN novel n ON nc.chapter_novelID = n.novel_id " +
                    "ORDER BY nc.id DESC LIMIT ? OFFSET ?";
            List<Map<String, Object>> chapters = jdbcTemplate.queryForList(sql, new Object[]{size, offset});

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Map<String, Object> chapter : chapters) {
                Date updateTime = (Date) chapter.get("update_time");
                String formattedTime = dateFormat.format(updateTime);
                chapter.put("update_time", formattedTime);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("totalPages", totalPages); // 总页数
            response.put("chapters", chapters); // 小说数据

            return ResponseEntity.ok(response); // 返回分页结果和总页数

        } catch (Exception e) {
            // 错误处理
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Error fetching chapters: " + e.getMessage());
            return ResponseEntity.status(201).body(errorResponse);
        }
    }


    private static Map<String, Object> getStringObjectMap(Integer total_novel, Integer total_chapter, Integer total_user) {
        Map<String, Integer> numres = new HashMap<>();
        numres.put("novel_num", total_novel);
        numres.put("chapter_num", total_chapter);
        numres.put("user_num", total_user);

        Map<String, String> developer = new HashMap<>();
        developer.put("developer_name", "言道子");
        developer.put("email", "1.0");
        developer.put("class", "Gitee");
        developer.put("school_id", "575732022");
        developer.put("email", "575732022@qq.com");
        developer.put("QQ", "575732022");
        developer.put("Weixin", "KzMnLz");
        developer.put("system_name", "大衍小说系统");
        developer.put("system_ver", "1.0");

        Map<String, Object> response = new HashMap<>();
        response.put("system_info", numres);
        response.put("developer_info", developer);
        return response;
    }


    private String getAdminToken(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return "";
        }
        // 从 Authorization 中提取 Bearer 令牌
        return authorization.substring(7);
    }
    private boolean isAdmin(String adminToken) {
        String decryptedData = null;
        try {
            decryptedData = AESCryptoUtil.decrypt(adminToken);
        } catch (Exception e) {
            return false;
        }
        String[] parts = decryptedData.split("\\."); // 分割用户名和密码

        if (parts.length != 2) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "无效的token格式");
            return false;
        }

        String username = parts[0];

        try {
            // 查询用户是否是管理员
            String sql = "SELECT 1 FROM admin WHERE username = ?";
            jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);
            // 如果查询成功执行到这里，说明用户是管理员
            return true;
        } catch (EmptyResultDataAccessException e) {
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    private ResponseEntity<Map<String, String>> buildErrorResponse(String message, int status) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", message);
        return ResponseEntity.status(status).body(errorResponse);
    }

    private ResponseEntity<Map<String, String>> buildSuccessResponse(String message) {
        Map<String, String> successResponse = new HashMap<>();
        successResponse.put("message", message);
        return ResponseEntity.ok(successResponse);
    }


}
